package org.sample.vm.gc;

/**
 * Escape garbage collection by finalize method.
 *
 */
public class FinalizeEscapeGC {

	public static FinalizeEscapeGC SAVE_HOOK = null;

	public void isAlive() {
		System.out.println("Yes, I am still alive.");
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		System.out.println("finalize method executed.");
		FinalizeEscapeGC.SAVE_HOOK = this;
	}

	public static void main(String[] args) throws Throwable {
		SAVE_HOOK = new FinalizeEscapeGC();
		triggerGC();
		triggerGC();
	}

	private static void triggerGC() throws InterruptedException {
		SAVE_HOOK = null;
		System.gc();

		Thread.sleep(5000);
		if (SAVE_HOOK != null) {
			SAVE_HOOK.isAlive();
		} else {
			System.out.println("No, I am dead.");
		}
	}

}
